//
//  IMB_AddPicView.m
//  SelectCameraView
//
//  Created by 刘泽琛 on 14-4-15.
//  Copyright (c) 2014年 刘 泽琛. All rights reserved.
//

#import "IMB_AddPicView.h"
#import <QuartzCore/QuartzCore.h>
#define columns 2
#define rows 3
#define itemsPerPage 12
#define space 20
#define gridHight 35
#define gridWith 35
#define unValidIndex  -1
#define threshold 30

@interface IMB_AddPicView(private)

-(NSInteger)indexOfLocation:(CGPoint)location;
-(CGPoint)orginPointOfIndex:(NSInteger)index;
-(void) exchangeItem:(NSInteger)oldIndex withposition:(NSInteger) newIndex;
@end

@implementation IMB_AddPicView

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}

- (void)awakeFromNib {
    self.imgArray = [[NSMutableArray alloc]initWithCapacity:0];
    page = 0;
    isEditing = NO;
    
    // BJGridItem +号
    UIImage *imageButton = [UIImage imageNamed:@"chuangjian10"];
    addbutton = [[BJGridItem alloc] initWithTitle:@"" withImage:imageButton atIndex:0 editable:NO isVideo:NO];
    addbutton.userInteractionEnabled = YES;
    [addbutton setFrame:CGRectMake(15, 8, 65, 65)];
    addbutton.delegate = self;
    
    //flag
    self.backgroundColor = [UIColor whiteColor];
    [self addSubview: addbutton];
    
    gridItems = [[NSMutableArray alloc] initWithCapacity:6];
    [gridItems addObject:addbutton];
    [self setPagingEnabled:YES];
    singletap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleSingleTap:)];
    [singletap setNumberOfTapsRequired:1];
    singletap.delegate = self;
    [self addGestureRecognizer:singletap];
    
    // 观察者
    [self addObserver:self forKeyPath:@"imgsCount" options:NSKeyValueObservingOptionNew context:NULL];
    [self addObserver:self forKeyPath:@"fileType" options:NSKeyValueObservingOptionNew context:NULL];
    [self addObserver:self forKeyPath:@"dynamicInt" options:NSKeyValueObservingOptionNew context:NULL];
}

- (id)init {
    if (self = [super init]) {
        // code...
    }
    return self;
}

#pragma mark Action
- (void)backUIImage:(BackImgArr)backImgs {
    self.backImgs = backImgs;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)fullDisPlayImg:(NSInteger)number item:(BJGridItem *)item {
    
    /*
    NSInteger count = self.imgArray.count;
    NSMutableArray *photos = [NSMutableArray arrayWithCapacity:count];
    for (int i = 0; i<count; i++) {
        MJPhoto *photo = [[MJPhoto alloc] init];
        photo.image = self.imgArray[i];
        photo.srcImageView = item;
        [photos addObject:photo];
    }
    
    MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
    browser.currentPhotoIndex = number;
    browser.photos = photos;
    [browser show];*/
}

- (void)normalDisplay {
    self.imgScrollView.hidden = YES;
}

// 动态操作 自定义相机拍照/摄像成功后，调用此方法
// 格式sendDict = @{@"fileData": @"无",@"fileImg":img,@"fileType":@"1"};
- (void)cameraAffirm:(NSDictionary *)receiveDict {
    receiveType = receiveDict[@"fileType"];
    // 1.判断接受字典中fileImg数组中的imgs个数--》@[fileImg]为数组
    // 2.检查block返回的数组
    if (receiveDict) {
        NSArray *imgs = receiveDict[@"fileImg"];
        for (int i = 0; i < imgs.count; i++) {
            UIImage *currentImg = imgs[i];
            self.image = currentImg;
            [self Addbutton];
        }
    }else {
        return;
    }
}

// 创建内容页
- (void)createPageSendImg:(UIImage *)img {
    self.image = img;
    [self Addbutton];
}

- (void)selectTakePhotoOrCamera:(TakePhotoOrCamera)isTakPhoto {
    self.isTakePhoto = isTakPhoto;
}

- (void)Addbutton {
    // 图片数组添加元素 检查图片个数
    [self.imgArray addObject:self.image];
    self.imgsCount = self.imgArray.count;
    // 检查是不是动态push进来，如不是限制图片和+号：显示1张图片后，+号去掉
    self.dynamicInt = [[NSUserDefaults standardUserDefaults]integerForKey:USERDEFAULTS_CLASSPARENT];
    if ([receiveType isEqualToString:@"0"]) {
        self.fileType = receiveType;
        self.isVideo = YES;
    }else {
        self.isVideo = NO;
    }
    // block回调
    self.backImgs(self.imgArray);
    
    // 图片数组大于9的话，改数组则移除第9张后面的

    if (self.imgArray.count > 9) {
        for (int i = 9; i < self.imgArray.count; i++) {
            [self.imgArray removeObjectAtIndex:i];
        }
    } else {
        CGRect frame = CGRectMake(15, 8, 65, 65);
        int n = [gridItems count];
        int row = (n-1) / 4;
        int col = (n-1) % 4;
        int curpage = (n-1) / itemsPerPage;
        row = row % 4;
        
        if (n / 12 + 1 > 1) {
            NSLog(@"不能创建更多页面");
        }else{
            frame.origin.x = frame.origin.x + frame.size.width * col + 10 * col + self.frame.size.width * curpage;
            frame.origin.y = frame.origin.y + frame.size.height * row + 10 * row;
            self.gridItem = [[BJGridItem alloc] initWithTitle:[NSString stringWithFormat:@"%d",n-1] withImage:self.image atIndex:n-1 editable:YES isVideo:self.isVideo];
            self.gridItem.userInteractionEnabled = YES;
            [self.gridItem setFrame:frame];
            [self.gridItem setAlpha:1];
            self.gridItem.delegate = self;
            [gridItems insertObject:self.gridItem atIndex:n-1];
            [self addSubview:self.gridItem];
            self.gridItem = nil;
            
            //move the add button
            row = n / 4;
            col = n % 4;
            curpage = n / 12;
            row = row % 4;
            frame = CGRectMake(15, 8, 65, 65);
            frame.origin.x = frame.origin.x + frame.size.width * col + 10 * col + self.frame.size.width * curpage;
            frame.origin.y = frame.origin.y + frame.size.height * row + 10 * row;
            [self scrollRectToVisible:CGRectMake(self.frame.size.width * curpage, self.frame.origin.y, self.frame.size.width, self.frame.size.height) animated:NO];
            [UIView animateWithDuration:0.2f animations:^{
                [addbutton setFrame:frame];
            }];
            addbutton.index += 1;
            
            // 此处判断 图片数组 的个数，根据其个数改变scrollview的frame
            if (self.imgArray.count < 4) {
                NSLog(@"按钮1行");
                self.frame = CGRectMake(0, _minY, 320, 81);
            }
            
            if (self.imgArray.count < 8 && self.imgArray.count >= 4) {
                NSLog(@"按钮2行");
                self.frame = CGRectMake(0, _minY, 320, 154);
            }
            
            if (self.imgArray.count < 9 && self.imgArray.count >= 8) {
                NSLog(@"按钮3行");
                self.frame = CGRectMake(0, _minY, 320, 229);
            }
        }
    }
}

#pragma mark-- BJGridItemDelegate 点击

- (void)gridItemDidClicked:(BJGridItem *)gridItem{
    
    // 点击方法触发是否添加item，还是全屏浏览图片
    if (gridItem.index == [gridItems count]-1) {
        self.isTakePhoto(YES);
    }else {
        [self fullDisPlayImg:gridItem.index item:gridItem];
    }
}

- (void)gridItemDidDeleted:(BJGridItem *)gridItem atIndex:(NSInteger)index{
    BJGridItem * item = [gridItems objectAtIndex:index];
    [gridItems removeObjectAtIndex:index];
    [UIView animateWithDuration:0.2 animations:^{
        CGRect lastFrame = item.frame;
        CGRect curFrame;
        for (int i = index; i < [gridItems count]; i++) {
            BJGridItem *temp = [gridItems objectAtIndex:i];
            curFrame = temp.frame;
            [temp setFrame:lastFrame];
            lastFrame = curFrame;
            [temp setIndex:i];
        }
        //[addbutton setFrame:lastFrame];
    }];
    [item removeFromSuperview];
    item = nil;
    
    //图片数组随即删除
    [self.imgArray removeObjectAtIndex:index];
    
    // 此处判断 图片数组 的个数，根据其个数改变scrollview的frame
    if (self.imgArray.count < 4) {
        NSLog(@"按钮1行");
        self.frame = CGRectMake(0, _minY, 320, 81);
    }
    if (self.imgArray.count < 8 && self.imgArray.count >= 4) {
        NSLog(@"按钮2行");
        self.frame = CGRectMake(0, _minY, 320, 154);
    }
    if (self.imgArray.count < 9 && self.imgArray.count >= 8) {
        NSLog(@"按钮3行");
        self.frame = CGRectMake(0, _minY, 320, 229);
    }
    self.imgsCount = self.imgArray.count;
    self.dynamicInt = [[NSUserDefaults standardUserDefaults]integerForKey:USERDEFAULTS_CLASSPARENT];
}

- (void)gridItemDidEnterEditingMode:(BJGridItem *)gridItem{
    for (BJGridItem *item in gridItems) {
        NSLog(@"%ld",(long)item.index);
        [item enableEditing];
    }
    isEditing = YES;
}

- (void)gridItemDidMoved:(BJGridItem *)gridItem withLocation:(CGPoint)point moveGestureRecognizer:(UILongPressGestureRecognizer *)recognizer{
    CGRect frame = gridItem.frame;
    CGPoint _point = [recognizer locationInView:self];
    frame.origin.x = _point.x - point.x;
    frame.origin.y = _point.y - point.y;
    gridItem.frame = frame;
    NSLog(@"gridItemframe:%f,%f",frame.origin.x,frame.origin.y);
    NSLog(@"move to point(%f,%f)",point.x,point.y);
    
    NSInteger toIndex = [self indexOfLocation:_point];
    NSInteger fromIndex = gridItem.index;
    NSLog(@"fromIndex:%ld toIndex:%ld",(long)fromIndex,(long)toIndex);
    
    if (toIndex != unValidIndex && toIndex != fromIndex) {
        BJGridItem *moveItem = [gridItems objectAtIndex:toIndex];
        [self sendSubviewToBack:moveItem];
        [UIView animateWithDuration:0.2 animations:^{
            CGPoint origin = [self orginPointOfIndex:fromIndex];
            //NSLog(@"origin:%f,%f",origin.x,origin.y);
            moveItem.frame = CGRectMake(origin.x, origin.y, moveItem.frame.size.width, moveItem.frame.size.height);
        }];
        [self exchangeItem:fromIndex withposition:toIndex];
    }
}

- (void) gridItemDidEndMoved:(BJGridItem *) gridItem withLocation:(CGPoint)point moveGestureRecognizer:(UILongPressGestureRecognizer*) recognizer{
    CGPoint _point = [recognizer locationInView:self];
    NSInteger toIndex = [self indexOfLocation:_point];
    if (toIndex == unValidIndex) {
        toIndex = gridItem.index;
    }
    CGPoint origin = [self orginPointOfIndex:toIndex];
    [UIView animateWithDuration:0.2 animations:^{
        gridItem.frame = CGRectMake(origin.x, origin.y, gridItem.frame.size.width, gridItem.frame.size.height);
    }];
    NSLog(@"gridItem index:%ld",(long)gridItem.index);
}

- (void) handleSingleTap:(UITapGestureRecognizer *) gestureRecognizer{
    if (isEditing) {
        for (BJGridItem *item in gridItems) {
            [item disableEditing];
        }
        [addbutton disableEditing];
    }
    isEditing = NO;
}


- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    if(touch.view != self){
        return NO;
    }else
        return YES;
}

#pragma mark-- private
- (NSInteger)indexOfLocation:(CGPoint)location{
    NSInteger index;
    NSInteger _page = location.x / 320;
    NSInteger row =  location.y / (gridHight + 20);
    NSInteger col = (location.x - _page * 320) / (gridWith + 20);
    if (row >= rows || col >= columns) {
        return  unValidIndex;
    }
    index = itemsPerPage * _page + row * 2 + col;
    if (index >= [gridItems count]) {
        return  unValidIndex;
    }
    
    return index;
}

- (CGPoint)orginPointOfIndex:(NSInteger)index{
    CGPoint point = CGPointZero;
    if (index > [gridItems count] || index < 0) {
        return point;
    }else{
        NSInteger _page = index / itemsPerPage;
        NSInteger row = (index - _page * itemsPerPage) / columns;
        NSInteger col = (index - _page * itemsPerPage) % columns;
        
        point.x = _page * 320 + col * gridWith + (col +1) * space;
        point.y = row * gridHight + (row + 1) * space;
        return  point;
    }
}

- (void)exchangeItem:(NSInteger)oldIndex withposition:(NSInteger)newIndex{
    ((BJGridItem *)[gridItems objectAtIndex:oldIndex]).index = newIndex;
    ((BJGridItem *)[gridItems objectAtIndex:newIndex]).index = oldIndex;
    [gridItems exchangeObjectAtIndex:oldIndex withObjectAtIndex:newIndex];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {

    // 判断当前是否是动态传过来的
    NSInteger dynamicValue = [[NSUserDefaults standardUserDefaults]integerForKey:USERDEFAULTS_CLASSPARENT];
    switch (dynamicValue) {
        case 10:
            // 当前版块是否为动态 10代表不是
            if ([keyPath isEqualToString:@"dynamicInt"]) {
                if (self.dynamicInt == 10 && self.imgArray.count != 0) {
                    addbutton.hidden = YES;
                }else {
                    addbutton.hidden = NO;
                }
            }
            break;
        default:
            // 判断图片为9张的时候hide
            if ([keyPath isEqualToString:@"imgsCount"]) {
                if (_imgsCount >= 9) {
                    addbutton.hidden = YES;
                }else {
                    addbutton.hidden = NO;
                }
            }
            // 是否是视频或图片
            if ([keyPath isEqualToString:@"fileType"]) {
                if ([_fileType isEqualToString:@"0"]) {
                    addbutton.hidden = YES;
                }else {
                    addbutton.hidden = NO;
                }
            }
            break;
    }
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"KHIDEKEYBOARDVIEW" object:nil];
    [self removeObserver:self forKeyPath:@"imgsCount" context:NULL];
    [self removeObserver:self forKeyPath:@"fileType" context:NULL];
    [self removeObserver:self forKeyPath:@"dynamicInt" context:NULL];
    addbutton.delegate = nil;
    addbutton = nil;
    self.gridItem.delegate = nil;
    self.gridItem = nil;
    self.imgArray = nil;

    NSLog(@"顺序添加图片View 释放...");
}

@end
